package sol.leetcode;

import utils.ArrayUtils;

/**
 * Game of Life
 */
public class Issue289 {
    public void gameOfLife(int[][] board) {

        int m = board.length;
        int n = board[0].length;

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                int lives = lives(board, i, j);
                if ((board[i][j] & 1) == 1 && (lives == 2 || lives == 3))
                    board[i][j] = 3;
                else if ((board[i][j] & 1) == 0 && lives == 3)
                    board[i][j] = 2;
            }
        }

        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                board[i][j] = board[i][j] >> 1;
    }

    private int lives(int[][] board, int i, int j) {

        int lives = 0;
        int m = board.length;
        int n = board[0].length;
        for (int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); ++x) {
            for (int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); ++y) {
                lives += board[x][y] & 1;
            }
        }

        lives -= board[i][j] & 1;
        return lives;
    }

    public static void main(String[] args) {
        int[][] board = {
                {0, 0, 0, 1},
                {0, 1, 1, 0},
                {1, 0, 1, 0},
                {0, 0, 0, 0}
        };

        Issue289 sol = new Issue289();
        sol.gameOfLife(board);

        ArrayUtils.print(board);
    }
}
